package com.ibm.iisp.common.dao;

import java.io.IOException;

import javax.persistence.AttributeConverter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ibm.iisp.common.util.JacksonObjectMapperFactory;

/**
 * 基类协助把一个复杂类型字段转换为JSON保存到数据库。 子类只需要指定实际字段类型就可用。
 * 
 * @author JohnnyZhou
 *
 * @param <T> 实际字段类型
 */
public abstract class AbstractJsonConverter<T> implements AttributeConverter<T, String> {
	protected ObjectMapper objectMapper = JacksonObjectMapperFactory.getObjectMapper();

	protected abstract Class<T> getType();
	@Override
	public String convertToDatabaseColumn(T val) {
		if (val == null) {
			return null;
		}
		try {
			return objectMapper.writeValueAsString(val);
		} catch (Exception ex) {
			throw new RuntimeException("JSON 转换出错:" + val, ex);
		}
	}

	@Override
	public T convertToEntityAttribute(String dbData) {
		if (dbData == null) {
			return null;
		}
		try {
			T readValue = objectMapper.readValue(dbData, getType());
			return readValue;
		} catch (IOException ex) {
			throw new RuntimeException("JSON to [" + getType() + "] 转换出错:" + dbData, ex);
		}
	}

}
